package com.cykj.consumer;


import com.cykj.dto.ResponseDTO;
import com.cykj.entity.CyOrderDO;
import com.cykj.feign.CyGoodControllerOpenFeign;
import com.cykj.mapper.OrderMapper;
import com.cykj.mqEvent.CancelOrderEvent;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(topic = "cancel-order",consumerGroup = "${rocketmq.consumer.group}")
public class CancelOrderConsumer implements RocketMQListener<CancelOrderEvent> {


    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private CyGoodControllerOpenFeign cyGoodControllerOpenFeign;

    @Override
    public void onMessage(CancelOrderEvent cancelOrderEvent) {
        int orderId = cancelOrderEvent.getOrderId();
        CyOrderDO orderDO = orderMapper.selectOrderById(orderId);
        if (orderDO.getPayState()!=1){ // 未支付
            // redis 回滚库存
            redisTemplate.opsForValue().increment("stock:"+orderDO.getGoodId(),orderDO.getBuyCount());
            // 修改订单状态为超时
            orderDO.setIsTimeOut(1);
            orderMapper.updateOrderIsTimeOut(orderDO);
        }else { // 已支付
            // 修改数据库库存
            ResponseDTO responseDTO = cyGoodControllerOpenFeign.updateGoodStock(orderDO.getGoodId(), orderDO.getBuyCount());
            System.err.println(responseDTO);
        }
    }
}
